import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/services/asset_bundle.dart';
import 'package:flutter_mode/ui/expansion_panel_demo.dart';
import 'package:flutter_mode/utils.dart';

class MaterialScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MaterialScreen();
  }
}

class _MaterialScreen extends State<MaterialScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  double _sliderValue = 0.3;
  bool _isCheckd = false;
  int _rvalue = 0;

  int _listCount = 5;

  var _images = <String>[
    'https://www.yimizi.xyz/wedding/image/only/7.webp',
    'https://www.yimizi.xyz/wedding/image/only/8.webp',
    'https://www.yimizi.xyz/wedding/image/only/34.webp'
  ];

  _changeChecked(bool? b) {
    setState(() {
      _isCheckd = b ?? false;
    });
  }

  _changeRvalue(int? i) {
    setState(() {
      _rvalue = i ?? 0;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    /*CustomScrollView(
      slivers: <Widget>[],
    )*/
    return Scaffold(
      appBar: AppBar(
        title: Text('material风'),
        centerTitle: true,
        bottom: TabBar(
          tabs: <Widget>[
            Tab(
              text: '小控件',
            ),
            Tab(
              text: 'ListView',
            ),
            Tab(
              text: 'GridView',
            )
          ],
          controller: _tabController,
        ),
      ),
      /*body: ,*/
      body: new Builder(builder: (context) {
        return TabBarView(controller: _tabController, children: <Widget>[
          CustomScrollView(
            slivers: <Widget>[
              SliverList(
                  delegate: SliverChildListDelegate(<Widget>[
                Wrap(
                  spacing: 8,
                  runSpacing: 4,
                  children: <Widget>[
                    Center(
                      child: Text('下面是按钮'),
                    ),
                    ElevatedButton(
                      onPressed: () {},
                      child: Text('ElevatedButton'),
                    ),
                    TextButton(
                        onPressed: () =>
                            _showAlert(context, 'ElevatedButton 无背景按钮，按下后显示圆角背景'),
                        child: Text('ElevatedButton')),
                    IconButton(
                      icon: Icon(Icons.add_alarm),
                      onPressed: () {},
                      tooltip: 'im icon button',
                      highlightColor: Colors.red,
                      splashColor: Colors.yellow,
                      color: Colors.blue,
                    ),
                    PopupMenuButton(
                      itemBuilder: (context) {
                        return <PopupMenuEntry>[
                          PopupMenuItem(
                            child: Text('da jiang san'),
                            value: 'dja',
                          ),
                          PopupMenuItem(
                            child: Text('da jiang san hao'),
                            value: 'djaf',
                          ),
                        ];
                      }, /*icon: Icon(Icons.home),*/
                    ),
                    RawMaterialButton(
                      onPressed: () => _showAlert(context,
                          'RawMaterialButton 带有Material点击效果的无背景按钮，建议用于ListView的item'),
                      child: Text('RawMaterialButton'),
                    ),
                    ButtonBar(
                      alignment: MainAxisAlignment.center,
                      children: <Widget>[
                        ElevatedButton(
                          onPressed: () {},
                          child: Text('这行是ButtonBar'),
                        ),
                        IconButton(icon: Icon(Icons.list), onPressed: null),
                        ElevatedButton(onPressed: () {}, child: null,),
                      ],
                    ),
                    Center(
                      child: Text('下面是输入和选项'),
                    ),
                    TextField(
                      onSubmitted: (s) {},
                      keyboardType: TextInputType.number,
                      textInputAction: TextInputAction.search,
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.all(5),
                        icon: Icon(Icons.text_fields),
                        labelText: '我是提示',
                        hintText: '这是输入框',
                        helperText: '请输入数字',
                      ),
                    ),
                    Checkbox(
                      value: _isCheckd,
                      onChanged: (m) => _changeChecked(m),
                      activeColor: Colors.yellow,
                    ),
                    Checkbox(
                      value: _isCheckd,
                      onChanged: (m) => _changeChecked(m),
                    ),
                    Radio(
                        value: 1,
                        groupValue: _rvalue,
                        onChanged: (m) => _changeRvalue(m as int)),
                    Radio(
                        value: 2,
                        groupValue: _rvalue,
                        onChanged: (m) => _changeRvalue(m as int)),
                    Switch(
                        value: _isCheckd, onChanged: (m) => _changeChecked(m)),
                    CheckboxListTile(
                        value: _isCheckd,
                        title: Text('I\'m CheckboxListTile'),
                        subtitle: Text('subtitle'),
                        controlAffinity: ListTileControlAffinity.leading,
                        onChanged: (m) => _changeChecked(m)),
                    RadioListTile(
                        value: 3,
                        groupValue: _rvalue,
                        title: Text('I\'m RadioListTile'),
                        subtitle: Text('subtitle'),
                        onChanged: (m) => _changeRvalue(m as int)),
                    SwitchListTile(
                      value: _isCheckd,
                      onChanged: (m) => _changeChecked(m),
                      title: Text('I\'m SwitchListTile'),
                      subtitle: Text('subtitle'),
                    ),
                    Slider(
                        value: _sliderValue,
                        onChanged: (d) {
                          setState(() {
                            _sliderValue = d;
                          });
                        }),
                    ElevatedButton(
                      onPressed: () {
                        showDatePicker(
                            context: context,
                            initialDate: DateTime.now(),
                            firstDate: DateTime(1990),
                            lastDate: DateTime(2030),
                            initialDatePickerMode: DatePickerMode.year);
                      },
                      child: Text('日期选择器'),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        showTimePicker(
                            context: context, initialTime: TimeOfDay.now());
                      },
                      child: Text('时间选择器'),
                    ),
                    Center(
                      child: Text('下面是弹窗'),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        // todo doc: https://docs.flutter.io/flutter/material/SimpleDialog-class.html
                        showDialog(
                            context: context,
                            builder: (context) {
                              return SimpleDialog(
                                title: Text('SimpleDialog'),
                                semanticLabel: 'What is this?',
                                children: <Widget>[
                                  SimpleDialogOption(
                                    child: Text('option 1'),
                                    onPressed: () => Navigator.pop(context),
                                  ),
                                  SimpleDialogOption(
                                    child: Text('option 2'),
                                    onPressed: () => Navigator.pop(context),
                                  ),
                                  SimpleDialogOption(
                                    child: Text('option 3'),
                                    onPressed: () => Navigator.pop(context),
                                  ),
                                ],
                              );
                            });
                      },
                      child: Text('SimpleDialog'),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        // todo doc: https://docs.flutter.io/flutter/material/AlertDialog-class.html
                        showDialog(
                            context: context,
                            builder: (context) {
                              return AlertDialog(
                                title: Text('AlertDialog'),
                                content: SingleChildScrollView(
                                  child: ListBody(
                                    children: <Widget>[
                                      Text('You will never be satisfied.'),
                                      Text(
                                          'You\’re like me. I’m never satisfied.'),
                                    ],
                                  ),
                                ),
                                actions: <Widget>[
                                  TextButton(
                                    child: Text('Regret'),
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                    },
                                  ),
                                  TextButton(
                                    child: Text('Ok'),
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                    },
                                  ),
                                ],
                              );
                            },
                            barrierDismissible: false);
                      },
                      child: Text('showDialog'),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        // todo doc: https://docs.flutter.io/flutter/material/BottomSheet-class.html
                        showModalBottomSheet(
                            context: context,
                            builder: (context) {
                              return BottomSheet(
                                  onClosing: () {},
                                  builder: (context) {
                                    return ListView.builder(
                                      itemBuilder: (context, po) {
                                        return Text('item $po');
                                      },
                                      itemCount: 5,
                                    );
                                  });
                            });
                      },
                      child: Text('BottomSheet'),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        Navigator.push(context,
                            MaterialPageRoute(builder: (context) {
                          return ExpansionPanelDemo();
                        }));
                      },
                      child: Text('ExpansionPanel'),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        // Scaffold.of(context)
                        //     .showSnackBar(SnackBar(content: Text('SnackBar')));
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('SnackBar')));
                      },
                      child: Text('SnackBar'),
                    ),
                    Center(
                      child: Text('下面是图片显示，参考：'),
                    ),
                    Center(
                      child: Text(
                          'https://blog.csdn.net/poorkick/article/details/80458707'),
                    ),
                    Image(
                      image: NetworkImage(_images[0]),
                      width: 100,
                      height: 100,
                    ),
                    Image.network(
                      _images[1],
                      width: 60,
                      height: 60,
                    ),
                    Image.asset(
                      'assets/img/icon_header.jpg',
                      width: 80,
                      height: 80,
                    ),
                    Image.asset(
                      'assets/img/fly_girl.jpeg',
                      width: 80,
                      height: 80,
                      bundle: myBundle,
                    ),
                    Image.asset(
                      'gogogo',
                      width: 80,
                      height: 80,
                      bundle: MyAssetBundle(),
                    ),
                    Image.asset(
                      'assets/img/3.0x/fly_girl.jpeg',
                      width: 80,
                      height: 80,
                    ),
                    Image.asset(
                      'assets/img/2.0x/youyu_girl.jpeg',
                      width: 80,
                      height: 80,
                    ),
                    Image.asset(
                      'assets/img/xiangrikui.jpg',
                      width: 80,
                      height: 80,
                    ),
                    Image.network(
                      _images[1],
                      width: 60,
                      height: 60,
                      color: Colors.red,
                      colorBlendMode: BlendMode.colorBurn,
                    ),
                    Image.asset(
                      'assets/img/girl_header1.jpg',
                      width: 170,
                      height: 170,

                      /// 拉升，替代安卓.9方案。显示大小必须大于图片大小，否则报错。
                      centerSlice:
                          Rect.fromCircle(center: Offset(50, 50), radius: 10),
                      fit: BoxFit.contain,
                    ),
                    Center(
                      child: Text('下面是其他展示控件'),
                    ),
                    Icon(Icons.add),
                    Chip(
                      avatar: CircleAvatar(
                        backgroundColor: Colors.grey.shade800,
                        child: Text('AB'),
                      ),
                      label: Text('Aaron Burr'),
                    ),
                    Tooltip(
                      message: 'Hello Tooltip',
                      child: Text('Tooltip'),
                    ),
                    ListTile(
                      leading: const Icon(Icons.event_seat),
                      title: const Text('The seat for the narrator'),
                    ),
                    LinearProgressIndicator(
                      value: 0.5,
                    ),
                    ElevatedButton(
                      onPressed: () {
                        pushMaterial(
                            context,
                            Scaffold(
                              body: Center(
                                child: InkWell(
                                  onTap: () {},
                                  child: Text('InkWell 包裹的类容不能有背景\n否则，水波效果被覆盖'),
                                ),
                              ),
                            ));
                      },
                      child: Text('水波效果'),
                    ),
                    ElevatedButton(
                      onPressed: () {},
                      child: Text(''),
                    ),
                  ],
                )
              ]))
            ],
          ),
          RefreshIndicator(
            child: ListView.builder(
              itemBuilder: _getChild,
              itemCount: _listCount,
            ),
            onRefresh: _loadData,
            semanticsLabel: 'semanticsLabel 是啥？',
            semanticsValue: 'semanticsValue 又是啥？',
          ),
          RefreshIndicator(
            child: GridView.builder(
              gridDelegate:
                  SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
              itemBuilder: (context, po) => Text('item $po'),
              itemCount: _listCount,
            ),
            onRefresh: _loadData,
            semanticsLabel: 'semanticsLabel 是啥？',
            semanticsValue: 'semanticsValue 又是啥？',
          ),
        ]);
      }),
    );
  }

  Future<void> _loadData() async {
    setState(() {
      _listCount += 1;
    });
  }
}

_showAlert(BuildContext context, String say) {
//    showAboutDialog(context: context, children: <Widget>[Text('sa')]);
  /*showGeneralDialog(context: context, pageBuilder: (context, an1, an2){
      return Text(say);
    });*/
  showDialog(
      context: context,
      builder: (context) => Center(
            child: Text(
              say,
              style: TextStyle(
                  fontSize: 15,
                  color: Colors.green,
                  decoration: TextDecoration.none),
            ),
          ),
      barrierDismissible: true);
}

Widget _getChild(BuildContext context, int position) {
  if (position == 0) {
    return Card(
      child: Image.asset(
        'assets/img/icon_header.jpg',
      ),
      color: Colors.brown,
    );
  }

  if (position % 5 == 0) {
    return Divider();
  }

  return ListTile(
    title: Text('item $position'),
    leading: Icon(Icons.home),
    onTap: () {},
  );
}

// 文件夹
// {"packages/cupertino_icons/assets/CupertinoIcons.ttf":["packages/cupertino_icons/assets/CupertinoIcons.ttf"],"assets/img/bg_red_pakage.png":["assets/img/bg_red_pakage.png"],"assets/img/xx/fly_girl.jpeg":["assets/img/3.0x/fly_girl.jpeg"],"assets/img/girl_header.jpg":["assets/img/girl_header.jpg"],"assets/img/icon_header.jpg":["assets/img/icon_header.jpg","assets/img/2.0x/icon_header.jpg","assets/img/3.0x/icon_header.jpg"],"assets/img/2.0x/icon_header.jpg":["assets/img/2.0x/icon_header.jpg"],"assets/img/3.0x/icon_header.jpg":["assets/img/3.0x/icon_header.jpg"],"assets/img/2.0x/xiangrikui.jpg":["assets/img/2.0x/xiangrikui.jpg"],"assets/img/2.0x/youyu_girl.jpeg":["assets/img/2.0x/youyu_girl.jpeg"]}
// 具体文件
// {"packages/cupertino_icons/assets/CupertinoIcons.ttf":["packages/cupertino_icons/assets/CupertinoIcons.ttf"],"assets/img/bg_red_pakage.png":["assets/img/bg_red_pakage.png"],"assets/img/fly_girl.jpeg":["assets/img/3.0x/fly_girl.jpeg"],"assets/img/girl_header.jpg":["assets/img/girl_header.jpg","assets/img/3.0x/girl_header.jpg"],"assets/img/icon_header.jpg":["assets/img/icon_header.jpg","assets/img/2.0x/icon_header.jpg","assets/img/3.0x/icon_header.jpg"],"assets/img/xiangrikui.jpg":["assets/img/2.0x/xiangrikui.jpg"],"assets/img/youyu_girl.jpeg":["assets/img/2.0x/youyu_girl.jpeg"]}
class MyAssetBundle extends PlatformAssetBundle {
  @override
  Future<ByteData> load(String key) {
    // TODO: implement load
    print("hhhhhhhhl- $key");
    return super.load(key);
  }

  @override
  Future<T> loadStructuredData<T>(
      String key, Future<T> Function(String value) parser) async {
    // TODO: implement loadStructuredData
    print("hhhhhhhhj- $key");
    T result = await super.loadStructuredData(key, parser);

    var tt = result as Map<String, List<String>>;
    tt.putIfAbsent("gogogo", () {
//      return ["assets/img/bg_red_pakage.png"];
//      return ["assets/img/2.0x/youyu_girl.jpeg"];
//      return ["assets/img/bg_red_pakage.png", "assets/img/2.0x/youyu_girl.jpeg"];
//      return ["assets/img/bg_red_pakage.png","assets/img/3.0x/girl_header.jpg"];
//      return ["assets/img/2.0x/youyu_girl.jpeg","assets/img/3.0x/girl_header.jpg"];
//      return ["assets/img/bg_red_pakage.png", "assets/img/2.0x/youyu_girl.jpeg","assets/img/3.0x/girl_header.jpg"];
      return ["assets/img/3.0x/girl_header.jpg", "assets/img/2.0x/youyu_girl.jpeg", "assets/img/bg_red_pakage.png"];
    });

    return result;
  }
}

final MyAssetBundle myBundle = MyAssetBundle();
